package com.xrf;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.system.as.application.system.basics.company.entity.MaCompanyEntity;
import com.system.as.application.system.basics.company.mapper.MaCompanyMapper;
import com.system.as.application.system.basics.user.entity.AsUserEntity;
import com.system.as.application.system.basics.user.service.UserService;
import com.system.as.application.system.request.company.ReqCompanyAdd;
import com.system.as.application.system.request.company.ReqCompanyModify;
import com.system.as.application.system.response.company.ResCompanyDetail;
import com.system.as.application.system.response.company.ResCompanyDown;
import com.system.core.common.EnumCode;
import com.system.core.common.ResultView;
import com.system.core.common.base.SystemServiceImpl;
import com.system.core.common.session.SessionUser;

@Service
public class MaCompanyService extends SystemServiceImpl<MaCompanyMapper, MaCompanyEntity> {
    private static Logger logger = LoggerFactory.getLogger(MaCompanyService.class);
    
    @Autowired
    private MaCompanyMapper companyMapper;
    
    @Autowired
    private UserService userService;
    
    @Transactional
    public ResultView insert(ReqCompanyAdd add) {
        ResultView view = null;
        MaCompanyEntity newEntity = new MaCompanyEntity();
        BeanUtils.copyProperties(add, newEntity);
        MaCompanyEntity old = super.getById(add.getCoCode());
        if (null != old && old.getCoCode() != null) {
            view = new ResultView(EnumCode.ERROR_9999, "添加单位失败, 单位编码已存在");
            return view;
        }
        if (StringUtils.isNotBlank(add.getParentCode())) {
            MaCompanyEntity pEntity = super.getById(add.getParentCode());
            if (pEntity == null) {
                view = new ResultView(EnumCode.ERROR_9999, "添加单位失败, 上级单位不存在");
                return view;
            }
            String allCoCode = pEntity.getAllCoCode() + "|" + add.getCoCode();
            newEntity.setAllCoCode(allCoCode);
        } else {
            String allCoCode = add.getCoCode();
            newEntity.setAllCoCode(allCoCode);
            newEntity.setParentCode(null);
        }
        newEntity.setCreateTime(new Date());
        boolean flag = save(newEntity);
        if (!flag) {
            view = new ResultView(EnumCode.ERROR_9999, "单位信息添加失败");
            return view;
        }
        view = new ResultView(EnumCode.SUCCESS);
        return view;
    }
    
    public ResultView selectListByParentCode(String coCode, String parentCode, Integer pageSize, Integer pageNum) {
        ResultView view = null;
        PageHelper.startPage(pageNum, pageSize);
        MaCompanyEntity entity = new MaCompanyEntity();
        entity.setParentCode(parentCode);
        QueryWrapper<MaCompanyEntity> queryWrapper = new QueryWrapper<MaCompanyEntity>(entity);
        if (StringUtils.isNotBlank(coCode)) {
            queryWrapper.like("CO_CODE", coCode);
        }
        queryWrapper.orderByDesc(" CREATE_TIME ");
        List<MaCompanyEntity> list = list(queryWrapper);
        PageInfo<MaCompanyEntity> page = new PageInfo<>(list);
        view = new ResultView(EnumCode.SUCCESS, page);
        return view;
    }
    
    public ResultView selectDownList(String coCode) {
        ResultView view = null;
        List<ResCompanyDown> list = companyMapper.selectDownList(coCode);
        view = new ResultView(EnumCode.SUCCESS, list);
        return view;
    }
    
    @Transactional
    public ResultView deleteMaCompany(String coCode) {
        ResultView result = null;
        MaCompanyEntity entity = super.getById(coCode);
        if (entity == null) {
            result = new ResultView(EnumCode.ERROR_9999, "单位信息不存在");
            return result;
        }
        List<MaCompanyEntity> companyList = companyMapper.selectByParentCoCode(coCode);
        if (companyList != null && companyList.size() > 0) {
            result = new ResultView(EnumCode.ERROR_9999, "存在下级单位，如果确实要删除，请先删除其下级单位");
            return result;
        }
        Integer count = companyMapper.deleteMaCompany(coCode);
        if (count == null || count <= 0) {
            result = new ResultView(EnumCode.ERROR_9999, "单位信息删除失败，单位信息不存在");
            return result;
        }
        // 5.删除单位下所有用户
        userService.delByCoCode(coCode);
        result = new ResultView(EnumCode.SUCCESS);
        return result;
    }
    
    @Transactional
    public ResultView updateMaCompany(ReqCompanyModify modify) {
        if (StringUtils.isBlank(modify.getParentCode())) {
            modify.setParentCode(null);
        }
        
        ResultView result = null;
        MaCompanyEntity entity = super.getById(modify.getCoCode());
        if (entity == null) {
            result = new ResultView(EnumCode.ERROR_9999, "单位信息不存在");
            return result;
        }
        BeanUtils.copyProperties(modify, entity);
        super.updateById(entity);
        result = new ResultView(EnumCode.SUCCESS);
        return result;
    }
    
    public ResultView getCompanyDetail(String coCode) throws ParseException {
        ResultView result = null;
        MaCompanyEntity entity = super.getById(coCode);
        if (entity == null) {
            result = new ResultView(EnumCode.ERROR_9999, "单位信息不存在");
            return result;
        }
        ResCompanyDetail detail = new ResCompanyDetail();
        BeanUtils.copyProperties(entity, detail);
        if (StringUtils.isNotBlank(entity.getParentCode())) {
            MaCompanyEntity parent = super.getById(entity.getParentCode());
            detail.setParentName(parent.getCoName());
        }
        result = new ResultView(EnumCode.SUCCESS);
        result.setData(detail);
        return result;
    }
    
    public ResultView selectByParentCoCode(String coCode) throws ParseException {
        ResultView result = null;
        List<MaCompanyEntity> companyList = companyMapper.selectByParentCoCode(coCode);
        result = new ResultView(EnumCode.SUCCESS, companyList);
        return result;
    }
    
    public ResultView getUserInvoiceCoDetail(SessionUser user) throws ParseException {
        AsUserEntity asUser = userService.getById(user.getUserId());
        return getCompanyDetail(asUser.getInvoiceCoCode());
    }
    
    public ResultView selectAllpCompany() {
        ResultView result = null;
        List<MaCompanyEntity> companyList = companyMapper.selectAllParentCompany();
        result = new ResultView(EnumCode.SUCCESS, companyList);
        return result;
    }
    
    public ResultView selectFirstCompany(Integer pageSize, Integer pageNum) {
        ResultView view = null;
        PageHelper.startPage(pageNum, pageSize);
        MaCompanyEntity entity = new MaCompanyEntity();
        QueryWrapper<MaCompanyEntity> queryWrapper = new QueryWrapper<MaCompanyEntity>(entity);
        queryWrapper.isNull("PARENT_CODE");
        queryWrapper.orderByDesc(" CREATE_TIME ");
        List<MaCompanyEntity> list = list(queryWrapper);
        PageInfo<MaCompanyEntity> page = new PageInfo<>(list);
        view = new ResultView(EnumCode.SUCCESS, page);
        return view;
    }
    
    public List<ResCompanyDown> selectCompanyTree(String coCode) {
        List<ResCompanyDown> companyList = companyMapper.selectDownList(coCode);
        if (companyList != null) {
            for (ResCompanyDown company : companyList) {
                company.setShowCompanyName("[" + company.getCoCode() + "]" + company.getCoName());
            }
            
            companyList = builTree(companyList, coCode);
        }
        return companyList;
    }
    
    private List<ResCompanyDown> builTree(List<ResCompanyDown> companyList, String coCode) {
        List<ResCompanyDown> treeList = new ArrayList<ResCompanyDown>();
        for (ResCompanyDown topModel : getRootNode(companyList, coCode)) {
            topModel = buildChilTree(topModel, companyList);
            treeList.add(topModel);
        }
        return treeList;
    }
    
    public List<ResCompanyDown> getRootNode(List<ResCompanyDown> companylList, String coCode) {
        List<ResCompanyDown> rootItemList = new ArrayList<ResCompanyDown>();
        for (ResCompanyDown company : companylList) {
            // 如果没有父节点，说明是根目录
            if (coCode.equals(company.getCoCode())) {
                rootItemList.add(company);
            }
        }
        return rootItemList;
    }
    
    private ResCompanyDown buildChilTree(ResCompanyDown topModel, List<ResCompanyDown> companyList) {
        List<ResCompanyDown> chilItemModels = topModel.getChildList();
        if (null == chilItemModels) {
            chilItemModels = new ArrayList<ResCompanyDown>();
        }
        for (ResCompanyDown model : companyList) {
            if (StringUtils.equalsIgnoreCase(model.getParentCode(), topModel.getCoCode())) {
                chilItemModels.add(buildChilTree(model, companyList));
            }
        }
        topModel.setChildList(chilItemModels);
        return topModel;
    }
}